package com.team.easybuy.filter;

import com.team.easybuy.entity.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@WebFilter(urlPatterns = {"/*"})
@Configuration
public class MyFilter implements Filter {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("uuid")) {
                    Long expire = redisTemplate.getExpire(cookie.getValue(), TimeUnit.MINUTES);
                    if (expire.intValue() < 5) {
                        User user = (User) redisTemplate.opsForValue().get(cookie.getValue());
                        redisTemplate.opsForValue().set(cookie.getValue(), user, 30, TimeUnit.MINUTES);
                    }
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
